import axios from '@peng_kai/kit/libs/axios';
import {
  checkCode,
  filterEmptyValue,
  formatPaging,
  getDeviceInfo,
  popupMessage,
  returnResultType,
  unitizeAxiosError,
} from '@peng_kai/kit/request/interceptors';
import { antdMessage } from '~/components/antd-assist';
import { flzxsqc, getCookieValue, setCookie } from '~/utils';
// import { useAdjustInit } from '~/components/provider/useAdjustInit'

export const server = axios.create({
  baseURL: import.meta.env.VITE_URL_PREFIX_main,
  timeout: 15 * 1000,
  // 自定义属性
  resultType: 'data',
  joinTime: true,
  errorMessage: true,
  successMessage: false,
  checkCode: true,
});

function getClickidValue() {
  const { searchParams } = new URL(location.href);
  const valueFromUrl = searchParams.get('click_id');
  const valueFromLocal = getCookieValue('clickid');

  if (valueFromUrl) {
    setCookie('clickid', valueFromUrl);
    return valueFromUrl;
  }
  else if (valueFromLocal) {
    return valueFromLocal;
  }
}

function getPlatform() {
  // 1Mobile 2Tablet 3Desktop 4TelegramBot
  if (envs.isTgApp)
    return 4;
  else if (envs.isIos || envs.isAndroid)
    return 1;
  else if (!envs.isIos && !envs.isAndroid)
    return 3;
  else
    return 0;
}

/* #B 请求拦截器（后 use 先执行） */
// 过滤掉查询参数中的空值
server.interceptors.request.use(...filterEmptyValue());
server.interceptors.request.use(...getDeviceInfo(base => flzxsqc(JSON.stringify(base))));

// 处理全局请求 Header
server.interceptors.request.use((req) => {
  // 删除多余的
  // ['Service-Name'].forEach((k) => req.headers.delete(k));
  // req.headers.set('uid', '1');
  req.headers.set('version', window.__APP_VERSION__ || '1.0.0');
  req.headers.set('lang', document.documentElement.lang);
  req.headers.set('clickid', getClickidValue());
  req.headers.set('platform', getPlatform());
  // req.headers.set('token', 'MTcyNDc1MTM5OXxOd3dBTkZwUU16UTJWVEpUUlZoTFJsVkpOMHRQUkRWRFNUTXpSalZYVGpKUVRWSkxVRTVQU1ZNM1RUTklSMFpKVlU1WFdVWk1Xa0U9fNvVQ5ZPOEJ1BHfhI__LWqJJf6pvgn8okv3miHlRS1zE');
  // 处理广告
  if (window.source && !~~getCookieValue('has_token')) {
    req.headers.set('source', window.source);
  }

  return req;
});
/* #E */

/* #B 响应拦截器（先 use 先执行） */
server.interceptors.response.use(...formatPaging());
server.interceptors.response.use(...unitizeAxiosError());
server.interceptors.response.use(...checkCode());
// 忽略指定错误 Code
server.interceptors.response.use(undefined, (error) => {
  /* 限制区域访问 */
  {
    const path = '/area-restricted.html';
    if (error.response?.data?.code === 31000 && location.pathname !== path) {
      location.pathname = path;
      throw error;
    }
  }

  /* 忽略部分错误 */
  {
    // 15001=未登录；
    const isIgnored = [15001].includes(error?.code);

    if (isIgnored) {
      error.data = { data: null };
      return error;
    }
    else {
      throw error;
    }
  }
});
server.interceptors.response.use(...popupMessage((type, msg) => antdMessage.open({ key: msg, type, content: msg })));
server.interceptors.response.use(...returnResultType());
/* #E */
